package com.misty.auth.config;

import com.misty.common.bean.Result;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Deprecated
@Component
public class MyAuthenticationFailure implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
        Result<?> result=null;
        if(e instanceof UsernameNotFoundException){
            result=Result.error(-1,e.getMessage());
        }else if(e instanceof BadCredentialsException){
            result=Result.error(-1,"密码错误!!");
        }else {
            result=Result.error(-1,e.getMessage());
        }
        //处理编码方式，防止中文乱码的情况
        httpServletResponse.setContentType("text/json;charset=utf-8");
        //返回给前台
        PrintWriter writer = httpServletResponse.getWriter();
//        writer.write(result);
        writer.flush();
        writer.close();
    }
}
